using Microsoft.AspNetCore.Mvc;
using McpApi.Services;

namespace McpApi.Controllers
{
    [ApiController]
    [Route("api/mcp")]
    public class MCPController : ControllerBase
    {
        private readonly MCPProtocolHandler _protocolHandler;
        private readonly ILogger<MCPController> _logger;

        public MCPController(MCPProtocolHandler protocolHandler, ILogger<MCPController> logger)
        {
            _protocolHandler = protocolHandler;
            _logger = logger;
        }

        /// <summary>
        /// MCP协议端点 - 接收JSON-RPC请求
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> HandleMCPRequest()
        {
            try
            {
                using var reader = new StreamReader(Request.Body);
                var requestBody = await reader.ReadToEndAsync();

                if (string.IsNullOrEmpty(requestBody))
                {
                    return BadRequest("Request body is empty");
                }

                _logger.LogDebug("收到MCP请求: {RequestBody}", requestBody);

                var response = await _protocolHandler.HandleRequestAsync(requestBody);

                return Content(response, "application/json");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理MCP请求时发生错误");
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 健康检查端点
        /// </summary>
        [HttpGet("health")]
        public IActionResult Health()
        {
            return Ok(new
            {
                status = "healthy",
                timestamp = DateTime.UtcNow,
                service = "MES MCP Server",
                version = "1.0.0"
            });
        }

        /// <summary>
        /// 服务信息端点
        /// </summary>
        [HttpGet("info")]
        public IActionResult Info([FromServices] IToolRegistry toolRegistry)
        {
            return Ok(new
            {
                serverInfo = new
                {
                    name = "MES MCP Server",
                    version = "1.0.0",
                    protocol = "MCP 2024-11-05"
                },
                capabilities = new
                {
                    tools = true,
                    resources = false,
                    prompts = false
                },
                statistics = new
                {
                    toolCount = toolRegistry.GetToolCount(),
                    uptime = DateTime.UtcNow
                }
            });
        }
    }
}
